package com.bjp.image.process;

import java.awt.image.RenderedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.bjp.image.model.ImageReady;
import com.bjp.image.service.ImageReadyLocalServiceUtil;
import com.liferay.portal.kernel.util.Base64;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.struts.PortletAction;
import com.liferay.util.servlet.ServletResponseUtil;

import com.liferay.portal.kernel.image.ImageBag;
import com.liferay.portal.kernel.image.ImageProcessorUtil;
import com.liferay.portal.kernel.util.ByteArrayMaker;
import com.liferay.portal.model.Image;
import com.liferay.portal.model.impl.ImageImpl;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageEncoder;
import com.liferay.portal.NoSuchImageException;

public class ViewImageProcess extends PortletAction {

	public ActionForward strutsExecute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		long imageId = ParamUtil.getLong(request, "imageId");
		String thumbnail = ParamUtil.getString(request, "size");
		int width = ParamUtil.getInteger(request, "width");
		int height = ParamUtil.getInteger(request, "height");
		boolean download =  ParamUtil.getBoolean(request, "download");
		boolean compressedView =  ParamUtil.getBoolean(request, "compressed");
		boolean originalView =  ParamUtil.getBoolean(request, "original");
		
		if (Validator.isNotNull(thumbnail)) {
			if (thumbnail.equalsIgnoreCase("small")) {
				width = 50;
				height = 70;
			} else if (thumbnail.equalsIgnoreCase("medium")) {
				width = 90;
				height = 120;
			} else if (thumbnail.equalsIgnoreCase("large")){
				width = 150;
				height = 180;
			}
		}

		if (Validator.isNotNull(imageId)) {
			ImageReady imageReady = ImageReadyLocalServiceUtil.getImageReady(imageId);
			if (imageReady != null) {
				response.setContentType(imageReady.getImageType());
				Image image = getImage((byte[]) Base64.decode(imageReady.getImage()), height, width);
				if (image == null) {
					throw new NoSuchImageException("Image is null");
				} else if (compressedView){
					ServletResponseUtil.write(response, image.getTextObj());
				} else if (download) {
					ServletResponseUtil.sendFile(response, imageId+"_photo", (byte[]) Base64.decode(imageReady.getImage()), imageReady.getImageType());
				} else if (originalView) {
					ServletResponseUtil.write(response, (byte[]) Base64.decode(imageReady.getImage()));
				}
			}
		}
		return null;
	}

	private static Image getImage(byte[] bytes, int width, int height) {
		try {
			ImageBag imageBag = ImageProcessorUtil.read(bytes);
			RenderedImage renderedImage = imageBag.getRenderedImage();
			String type = imageBag.getType();
			if (renderedImage == null) {
				throw new IOException("Unable to retreive image from input stream with type: "+ type);
			}
			if (height == 0 || width == 0) {
				height = renderedImage.getHeight();
				width = renderedImage.getWidth();
			}
			int size = bytes.length;
			Image image = new ImageImpl();
			image.setTextObj(scalemage(renderedImage, type, width, height));
			image.setType(type);
			image.setHeight(height);
			image.setWidth(width);
			image.setSize(size);
			return image;
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	private static byte[] scalemage(RenderedImage renderedImage, String contentType, int width, int height) {
		ByteArrayMaker bam = new ByteArrayMaker();
		try {
			RenderedImage thumbnail = ImageProcessorUtil.scale(renderedImage, width, height);
			if (contentType.indexOf("bmp") != -1) {
				ImageEncoder encoder = ImageCodec.createImageEncoder("BMP",	bam, null);
				encoder.encode(thumbnail);
			} else if (contentType.indexOf("gif") != -1) {
				ImageProcessorUtil.encodeGIF(thumbnail, bam);
			} else if (contentType.indexOf("jpg") != -1	|| contentType.indexOf("jpeg") != -1) {
				ImageIO.write(thumbnail, "jpeg", bam);
			} else if (contentType.indexOf("png") != -1) {
				ImageIO.write(thumbnail, "png", bam);
			} else if (contentType.indexOf("tif") != -1) {
				ImageEncoder encoder = ImageCodec.createImageEncoder("TIFF", bam, null);
				encoder.encode(thumbnail);
			}
		} catch (Exception e) {
			//
		}
		return bam.toByteArray();
	}
}